/**
 * Created by wzh on 2016/7/9.
 */
'use strict'
swan_pc
    .controller('OpportunityController',function($scope,OppInfo,ContactInfo,CompanyInfo,$rootScope,$state,$timeout,DateUtils,$filter,ngDialog,Clip,$q){
        $scope.opps;
        $scope.presentOppInfo;
        $scope.contactBaseInfos;
        $scope.companyInfos;
        $scope.sortedCompanyInfos;
        $scope.addOpp;
        $scope.dataStruct=[
            {
                name:"基本信息",
                type:"normal",
                blockName:"oppBaseInfo",
                struct:[
                    {
                        name:"项目名称",
                        key: "oppName",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name: "项目代码",
                        key: "oppCode",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"项目简介",
                        key: "overview",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"预算",
                        key: "budget",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"期望收入",
                        key: "expectRevenue",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"操控类型",
                        key: "controllerType",
                        option:3,
                        select:[
                            {
                                name:"我自己",
                                value:"我自己"
                            },
                            {
                                name:"公司",
                                value:"公司"
                            }],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"竞争强度",
                        key: "competition",
                        option:1,
                        select:[
                            {
                                name:"平和",
                                value:"平和"
                            },
                            {
                                name:"激烈",
                                value:"激烈"
                            },
                            {
                                name:"很激烈",
                                value:"很激烈"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"现状",
                        key: "reality",
                        option:3,
                        select:[
                            {
                                name:"OPEN",
                                value:"OPEN"
                            },
                            {
                                name:"WIN",
                                value:"WIN"
                            },
                            {
                                name:"LOST",
                                value:"LOST"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"属性",
                        key: "attribute",
                        option:3,
                        select:[
                            {
                                name:"LEAD",
                                value:"LEAD"
                            },
                            {
                                name:"OPP",
                                value:"OPP"
                            }
                        ],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:"",
                    },
                    {
                        name:"胜算",
                        key: "odds",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"需求",
                        key: "requirement",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"货币单位",
                        key: "unit",
                        option:1,
                        select:[],
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    },
                    {
                        name:"复杂程度",
                        key: "type",
                        option:1,
                        select:"",
                        show:[
                            {
                                name:"简单",
                                value:"简单"
                            },
                            {
                                name:"一般",
                                value:"一般"
                            },
                            {
                                name:"复杂",
                                value:"复杂"
                            },
                            {
                                name:"很复杂",
                                value:"很复杂"
                            }
                        ],
                        preview:0,
                        preBefore:"",
                        preAfter:""
                    }
                ]
            },
            {
                name:"日期信息",
                type:"repeat",
                blockName:"oppDateList",
                preName:"日期",
                struct:[
                    {
                        name:"日期类型",
                        key:"name",
                        option:3,
                        select:[
                            {
                                name:"卖标书的日期",
                                value:"卖标书的日期"
                            },
                            {
                                name:"开标日期",
                                value:"开标日期"
                            },
                            {
                                name:"宣布中标结果的日期",
                                value:"宣布中标结果的日期"
                            },
                            {
                                name:"Early Close",
                                value:"Early Close"
                            },
                            {
                                name:"Final Close",
                                value:"Final Close"
                            },
                            {
                                name:"用户发票最晚日期",
                                value:"用户发票最晚日期"
                            },
                            {
                                name:"用户结帐最晚日期",
                                value:"用户结帐最晚日期"
                            }
                        ],
                        show:[],
                        preview:3,
                        preBefore:"",
                        preAfter:":"
                    },
                    {
                        name:"日期",
                        key:"date",
                        option:2,
                        select:"",
                        show:[],
                        preview:2,
                        preBefore:"",
                        preAfter:""
                    }
                ]
            }
            /*{
                name:"交易",
                type:"repeat",
                blockName:"oppTradesList",
                preName:"交易",
                struct:[
                    {
                        name:"产品编号",
                        key:"productId",
                        option:1,
                        select:"",
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:":"
                    },
                    {
                        name:"折扣",
                        key:"discount",
                        option:1,
                        show:[],
                        preview:4,
                        preBefore:"(",
                        preAfter:"折)"
                    },
                    {
                        name:"count",
                        key:"",
                        option:1,
                        select:"",
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:":"
                    },
                    {
                        name:"成交价格",
                        key:"finalPrice",
                        option:1,
                        select:"",
                        show:[],
                        preview:0,
                        preBefore:"",
                        preAfter:":"
                    }
                ]
            },*/
        ]
        //初始化
        $scope.dirty={};
        $scope.initDirty=function() {
            $rootScope.oppDirty = false;
            $scope.dirty.oppBaseInfo=false;
            $scope.dirty.oppTradesList=false;
            $scope.dirty.oppContact=false;
            $scope.dirty.oppDateList=false;
        }
        $scope.initDirty();
        //排序
        $scope.sort=function(array) {
            $scope.sortedCompanyInfos = [];
            for (var i = 0; i < array.length; i++) {
                $scope.sortedCompanyInfos.push(array[i])
            }
            for (var i = 0; i < $scope.sortedCompanyInfos.length; i++) {
                if ($scope.sortedCompanyInfos[i].subCompanys.length > 0) {
                    angular.forEach($scope.sortedCompanyInfos[i].subCompanys, function (data) {
                        $scope.sortedCompanyInfos.push(data);
                    })
                }
            }
        }
        //加载
        $scope.loadAll=function(){
            OppInfo.query({infoid:"all"},function(result) {
                $scope.opps=result;
            })
            ContactInfo.query(function(result) {
                $scope.contactBaseInfos = result;
            })
            CompanyInfo.query({infoid:"all"},function(result) {
                $scope.companyInfos = result;
                $scope.sort(result);
            })
            Clip.query({page:0, size: 500, sort: ['id' + ',' + 'asc', 'id']}, function(result){
                $scope.oppClipNumber={};
                angular.forEach(result, function (data) {
                    if (data.relatedOpp!=undefined&&data.relatedOpp!=""){
                        var cid=data.relatedOpp.split(":")[0];
                        if ($scope.oppClipNumber[cid]!=undefined) $scope.oppClipNumber[cid]++;
                        else $scope.oppClipNumber[cid]=1;
                        console.log($scope.oppClipNumber[cid])
                    }
                })
            })
            if($rootScope.toState.name=="companyoppdetail") $scope.updatePresentOpp($scope.oppInCompanyId);
        }
        $scope.updatePresentOpp=function(id){
            OppInfo.queryAll({infoid:id},function(result){
                $scope.presentOppInfo=result;
                $scope.oppInfoPointer={
                    oppBaseInfo:result.opportunity,
                    oppTradesList:result.trades,
                    oppDateList:result.opportunityDates
                }
            })
        }
        $scope.clear=function () {
            $scope.addOpp={
                "competitorContactId": null,
                "competitorId": null,
                "customerContactId": null,
                "customerId": null,
                "headquarterId": null,
                "opportunity": {
                    "attribute": "",
                    "budget": null,
                    "competition": "",
                    "controllerType": "",
                    "expectRevenue": null,
                    "odds": "",
                    "oppCode": "",
                    "oppName": "",
                    "overview": "",
                    "reality": "",
                    "requirement": "",
                    "type": "",
                    "unit": ""
                },
                "opportunityDates": [
                    {
                        "date": "",
                        "name": "卖标书的日期",
                    },
                    {
                        "date": "",
                        "name": "开标日期",
                    },
                    {
                        "date": "",
                        "name": "宣布中标结果的日期",
                    },
                    {
                        "date": "",
                        "name": "Early Close",
                    },
                    {
                        "date": "",
                        "name": "Final Close",
                    },
                    {
                        "date": "",
                        "name": "用户发票最晚日期",
                    },
                    {
                        "date": "",
                        "name": "用户结帐最晚日期",
                    }
                ],
                "partnerContactId": null,
                "partnerId": null,
                /*"trades": [
                    {
                        "count": null,
                        "discount": null,
                        "finalPrice": null,
                        "productId": null,
                    }
                ],*/
                "userId": null
            }
        }
        $scope.refresh=function(){
            $scope.clear();
            $scope.loadAll();
        }
        $scope.refresh();
        //切换，新建，更新机会
        $scope.changeOpp=function(id){
            if($rootScope.toState.name=="companyopp") $scope.setCompanyInCompanyId(id);
            else {
                $scope.tabActive=1;
                $scope.updatePresentOpp(id);
            }
            if($rootScope.toState.name=="companyopp") $state.go("companyoppdetail");
            else $state.go("opportunitydetail");
        }
        $scope.updateOppInfo=function(){
            OppInfo.update({},$scope.presentOppInfo,function(result){
                alert("保存成功！");
                $scope.initDirty();
                $scope.updatePresentOpp(result.id);
            },function(result){
                alert("保存失败！"+result.message);
            })
        }
        $scope.saveOppInfo=function(){
            if($rootScope.toState.name=="companyaddopp"){
                $scope.addOpp.customerId=$scope.presentCompanyInfo.id;
            }
            OppInfo.save({},$scope.addOpp,function(result){
                alert("保存成功！");
                $scope.refresh();
                $scope.initDirty();
                $scope.updatePresentOpp(result.id);
                if($rootScope.toState.name=="companyaddopp") $state.go("companyopp");
                else $state.go("opportunitydetail");
            },function(result){
                alert("保存失败！"+result.message);
            })
        }
        $scope.resetOppInfo=function(id){
            if($rootScope.oppDirty)
                if(!confirm("有数据未保存，确定要重置么")) return false;
            $scope.updatePresentOpp(id);
            $scope.initDirty();
        }
        //获取公司或者联系人
        $scope.getCompanyNameById=function(id){
            var name="";
            if(id==""||id==undefined) return name;
            angular.forEach($scope.sortedCompanyInfos,function(data) {
                if (data.id==id) name=data.companyBaseInfo.name;
            });
            return name;
        }
        $scope.getContactById=function(id){
            var cont;
            angular.forEach($scope.contactBaseInfos,function(data) {
                if (data.id==id) cont=data;
            });
            return cont;
        }
        $scope.getCompanyById=function(id){
            var comp;
            angular.forEach($scope.sortedCompanyInfos,function(data) {
                if (data.id==id) comp=data;
            });
            return comp;
        }
        $scope.getContactNameById=function(id){
            var name;
            angular.forEach($scope.contactBaseInfos,function(data) {
                if (data.id==id) name=data.baseInfo.name;
            });
            return name;
        }
        //筛选查脏
        $scope.initFilter=function() {
            $scope.filterInfos = {
                name: "",
                one: {
                    a: false,
                    b: false,
                    c: false,
                    d: false,
                    e: false
                },
                two: {
                    a: false,
                    b: false,
                    c: false,
                    d: false,
                    e: false
                },
                three: {
                    a: false,
                    b: false,
                    c: false,
                    d: false,
                    e: false
                },
                four: {
                    a: false,
                    b: false,
                    c: false,
                    d: false,
                    e: false
                }
            }
        }
        $scope.initFilter();
        $scope.infoFilter=function(item) {
            if (item.opportunity.oppName.indexOf($scope.filterInfos.name) < 0) return false;
            if($rootScope.toState.name=="companyopp"&&item.customerId!=$scope.presentCompanyInfo.id) return false;
            if (!(!$scope.filterInfos.one.a && !$scope.filterInfos.one.b && !$scope.filterInfos.one.c && !$scope.filterInfos.one.d && !$scope.filterInfos.one.e
                || item.opportunity != undefined && (
                $scope.filterInfos.one.a && item.opportunity.reality == "LOST" ||
                $scope.filterInfos.one.b && item.opportunity.reality == "WIN" ||
                $scope.filterInfos.one.c && item.opportunity.reality == "OPEN" ||
                $scope.filterInfos.one.d && item.opportunity.reality == "" ||
                $scope.filterInfos.one.e && item.opportunity.reality == ""))) return false;
            if (!(!$scope.filterInfos.two.a && !$scope.filterInfos.two.b && !$scope.filterInfos.two.c && !$scope.filterInfos.two.d && !$scope.filterInfos.two.e
                || item.opportunity != undefined && (
                $scope.filterInfos.two.a||
                parseInt($scope.filterInfos.two.b && item.opportunity.odds.substring(0,2))>59||
                parseInt($scope.filterInfos.two.c && item.opportunity.odds.substring(0,2))>79))) return false;
            if (!(!$scope.filterInfos.three.a && !$scope.filterInfos.three.b && !$scope.filterInfos.three.c && !$scope.filterInfos.three.d && !$scope.filterInfos.three.e
                || item.opportunity != undefined && (
                $scope.filterInfos.three.a && item.opportunity.controllerType == "我自己" ||
                $scope.filterInfos.three.b && item.opportunity.controllerType == "公司" ||
                $scope.filterInfos.three.c  ))) return false;
            if (!(!$scope.filterInfos.four.a && !$scope.filterInfos.four.b && !$scope.filterInfos.four.c && !$scope.filterInfos.four.d && !$scope.filterInfos.four.e
                || item.opportunity != undefined && (
                $scope.filterInfos.four.a && item.opportunity.controllerType == "我自己" ||
                $scope.filterInfos.four.b && item.opportunity.controllerType == "公司"  ))) return false;
            return true;
        }
        $scope.dirtySet=function(index) {
            $rootScope.oppDirty=true;
            $scope.dirty[index]=true;
        }
        $scope.dirtyGet=function(index){
            return $scope.dirty[index];
        }
        $scope.colorRed={
            "color":"red"
        }
        $scope.colorDefault={}
        $scope.addOpportunity=function(){
            if($rootScope.toState.name=="companyopp"){
                $state.go("companyaddopp");
            }
            else {
                $scope.tabActive=2;
                $state.go("addopportunity");
            }
        }
        $scope.back=function (){
            $scope.refresh();
            $rootScope.goSref("opportunitylist")
        }
        //选择相关联系人或者公司
        $scope.selectContact=function(name,company){
            if($scope.presentOppInfo[name]!=undefined&&$scope.presentOppInfo[name]>0) $scope.selectedContact= $scope.getContactById($scope.presentOppInfo[name]);
            else $scope.selectedContact=undefined;
            $scope.resultArray={};
            $scope.filterCompany=company;
            ngDialog.open({
                templateUrl:"scripts/components/myself/opportunity/dialog/contactDialog.html",
                scope:$scope,
                controller:["$scope",function($scope){
                    $scope.closeContactDialog=function(){
                        if ($scope.selectedContact==undefined){
                            ngDialog.closeAll();
                            return;
                        }
                        $scope.presentOppInfo[name]=$scope.selectedContact.id;
                        $scope.dirtySet("oppContact");
                        ngDialog.closeAll();
                    }
                }]
            })
        }
        $scope.selectCompany=function(name){
            if($scope.presentOppInfo[name]!=undefined&&$scope.presentOppInfo[name]>0) $scope.selectedCompany= $scope.getCompanyById($scope.presentOppInfo[name]);
            else $scope.selectedCompany=undefined;
            $scope.resultArray={};
            ngDialog.open({
                templateUrl:"scripts/components/myself/opportunity/dialog/companyDialog.html",
                scope:$scope,
                controller:["$scope",function($scope){
                    $scope.closeCompanyDialog=function(){
                        if ($scope.selectedCompany==undefined){
                            ngDialog.closeAll();
                            return;
                        }
                        $scope.presentOppInfo[name]=$scope.selectedCompany.id;
                        $scope.dirtySet("oppDate");
                        ngDialog.closeAll();
                    }
                }]
            })
        }
        //获取顶级公司
        function getTop(id) {
            var comp=$scope.getCompanyById(id);
            if (comp.companyBaseInfo.isTop==true||comp.parentCompanyId==undefined||comp.parentCompanyId==0) return comp.companyBaseInfo.name;
            else return getTop(comp.parentCompanyId);
        }
        $scope.getTopName=function(id){
            var comp=$scope.getCompanyById(id);
            if (comp==undefined||comp.companyBaseInfo.isTop==true||comp.parentCompanyId==undefined||comp.parentCompanyId==0) return;
            else return getTop(comp.parentCompanyId);
        }
        //表单disabled控制
        $scope.checkDis=function(){
            if ($scope.addOpp.opportunity.oppName=="") return true;
            if ($scope.addOpp.opportunity.oppCode=="") return true;
            for (var i=0;i<7;i++){
                if ($scope.addOpp.opportunityDates[i].date=="") return true;
            }
            return false;
        }
        $scope.changeTabActive=function(tab){
            if ($scope.presentOppInfo==undefined&&tab!=2&&tab<5) {
                alert("您还没有选择任何项目");
                return;
            }
            var oldtab=$scope.tabActive;
            var result=true;
            $scope.tabActive=tab;
            if(tab==1) result=$rootScope.goSref('opportunitydetail');
            else if(tab==2) result=$rootScope.goSref('addopportunity');
            else if(tab==3) result=$rootScope.goSref('opptask');
            else if(tab==4) result=$rootScope.goSref('oppclip');
            else result=$rootScope.goSref('opportunitylist');
            if(!result) $scope.tabActive=oldtab;
        }
        //Excel 代码经过压缩，直接用，无需读
        function datenum(v, date1904) {
            if (date1904) {
                v += 1462;
            }
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        }
        function sheet_from_array_of_arrays(data) {
            var ws = {};
            var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
            for (var R = 0; R !== data.length; ++R) {
                for (var C = 0; C !== data[R].length; ++C) {
                    if (range.s.r > R) {
                        range.s.r = R;
                    }
                    if (range.s.c > C) {
                        range.s.c = C;
                    }
                    if (range.e.r < R) {
                        range.e.r = R;
                    }
                    if (range.e.c < C) {
                        range.e.c = C;
                    }
                    var cell = {v: data[R][C]};
                    if (cell.v === null) {
                        continue;
                    }
                    var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                    if (typeof cell.v === 'number') {
                        cell.t = 'n';
                    } else if (typeof cell.v === 'boolean') {
                        cell.t = 'b';
                    } else if (cell.v instanceof Date) {
                        cell.t = 'n';
                        cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else {
                        cell.t = 's';
                    }

                    ws[cell_ref] = cell;
                }
            }
            if (range.s.c < 10000000) {
                ws['!ref'] = XLSX.utils.encode_range(range);
            }
            return ws;
        }
        function Workbook() {
            if (!(this instanceof Workbook)) {
                return new Workbook();
            }
            this.SheetNames = [];
            this.Sheets = {};
        }
        //处理数据部分
        $scope.downExcel = function () {
            var d=$q.defer();
            var p=d.promise;
            var t=[];
            var f=0;
            for(var i=0;i<$scope.opps.length;i++){
                OppInfo.queryAll({infoid:$scope.opps[i].id},function(result){
                    t.push(result);
                    f++;
                    if (f==$scope.opps.length) d.resolve(t);
                },function (result) {
                    d.reject("网络连接错误")
                })
            }
            p.then(function(t){
                createExcel(t, '项目机会.xlsx')
            },function(r){
                alert("导出失败:"+r);
            });
        };
        function reGetDepartment(content,s,p,offset){
            for (var y in p){
                var row=[];
                for (var i=0;i<offset;i++) row.push("")
                for (var x in s){
                    row=row.concat([s[x].name,p[y][s[x].key]]);
                }
                row=row.concat(["子部门数量",p[y].subDepartments.length]);
                content.push(row);
                if (p[y].subDepartments.length>0) reGetDepartment(content,s,p[y].subDepartments,offset+1);
            }
        }
        function getHead(){
            var head=[];
            _.forEach($scope.dataStruct,function(item){
                if (item.blockName=="oppDateList") {
                    for (var i=1;i<8;i++) {
                        head.push("日期名称-"+i);
                        head.push("日期-"+i);
                    }
                }
                else{
                    head=head.concat(
                        _.map(item.struct,function(n){
                            return n.name;
                        })
                    );
                }
            })
            head=head.concat(["客户(公司)","客户(公司)联系人","合作者(公司)","合作者(公司)联系人","竞争者(公司)","竞争者(公司)联系人"])
            return head;
        }
        function getBody(data) {
            var body=[];
            for (var i=0;i<$scope.dataStruct.length;i++){
                var struct=$scope.dataStruct[i].struct;
                if ($scope.dataStruct[i].type=="normal"){
                    _.forEach(struct,function(item){
                        body.push(data.opportunity[item.key]);
                    })
                }
                else if ($scope.dataStruct[i].type=="repeat"){
                    data.opportunityDates=_.orderBy(data.opportunityDates,["name"],["asc"])
                    _.forEach(data.opportunityDates,function(item){
                        _.forEach(struct,function(it){
                            body.push(item[it.key])
                        })
                    })
                }
            }
            body=body.concat([$scope.getCompanyNameById(data.customerId),$scope.getContactNameById(data.customerContactId),$scope.getCompanyNameById(data.partnerId),$scope.getContactNameById(data.partnerContactId),$scope.getCompanyNameById(data.competitorId),$scope.getContactNameById(data.competitorContactId)])
            return body;
        }
        function createExcel(data, file_path) {
            var head=getHead();
            var body=[]
            var wb = new Workbook();
            for (var x in data){
                body.push(getBody(data[x]))
            }
            var array = [head,].concat(body);
            console.log(array)
            var ws = sheet_from_array_of_arrays(array);
            var ws_name = "项目机会";
            wb.SheetNames.push(ws_name);
            wb.Sheets[ws_name] = ws;
            var wopts = {bookType: 'xlsx', bookSST: true, type: 'binary'};
            var wbout = XLSX.write(wb, wopts);

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            /* the saveAs call downloads a file on the local machine */
            saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), file_path)
        }
        function sheet_to_data(workbook) {
            var result = null;
            $scope.body=[];
            $scope.head=[];
            workbook.SheetNames.forEach(function (sheetName) {
                var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1, raw: true});
                if (!_.isArray(json) || json.length < 2)return;
                $scope.head = json[0];
                $scope.body = json.slice(1);
            })
            if (_.xor(getHead(),$scope.head).length>0) {
                alert("文件头部错误");
                return false;
            }
            ngDialog.open({
                templateUrl:"scripts/components/myself/opportunity/dialog/uploadOppDialog.html",
                scope:$scope,
                controller:["$scope",function($scope){
                    var df=$q.defer();
                    var pm=df.promise;
                    $scope.solved=0;
                    $scope.check=new Array($scope.body.length);
                    $scope.exist=new Array($scope.body.length);
                    $scope.checkExist=function () {
                        for (var i in $scope.body){
                            for (var y=0;y<$scope.opps.length;y++){
                                if ($scope.body[i][1]==$scope.opps[y].opportunity.oppCode) $scope.exist[i]=true;
                            }
                        }
                    }
                    $scope.checkExist();
                    $scope.length=0;
                    $scope.pushOrPop=function($index) {
                        if($scope.check[$index]==1){
                            $scope.length++;
                        }
                        else $scope.length--;
                    }
                    $scope.checkAll=function (){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i]=1;
                        }
                        $scope.length=$scope.check.length;
                    }
                    $scope.unCheckAll=function (){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i]=0;
                        }
                        $scope.length=0;
                    }
                    $scope.reCheckAll=function(){
                        for (var i=0;i<$scope.check.length;i++){
                            $scope.check[i] = $scope.check[i] ==1?0:1;
                        }
                        $scope.length=$scope.check.length-$scope.length
                    }
                    $scope.checkAllUnexist=function(){
                        for (var i=0;i<$scope.check.length;i++){
                            if(!$scope.exist[i]) {
                                if ($scope.check[i] != 1) {
                                    $scope.check[i] = 1;
                                    $scope.length++;
                                }
                            }
                        }
                    }
                    $scope.getOppIdByOpcode=function(opcode){
                        var id=0;
                        _.forEach($scope.opps,function(item){
                            if (item.opportunity.oppCode==opcode) id=item.id;
                        })
                        return id;
                    }
                    $scope.uploadDate=function(row){
                        $scope.clear();
                        var a=$scope.addOpp;
                        var p=0;
                        _.forEach($scope.dataStruct,function(item){
                            if (item.type=="normal") {
                                _.forEach(item.struct,function(i){
                                    a.opportunity[i.key]=row[p++]
                                })
                            }
                            else if(item.type=="repeat") {
                                for (var i=0;i<7;i++) {
                                    a.opportunityDates[i].name = row[p++];
                                    a.opportunityDates[i].date = row[p++];
                                }
                            }
                        })
                        console.log(a);
                        OppInfo.save({},a, function(result){
                            $scope.solved++;
                            if($scope.solved==$scope.length) df.resolve($scope.solved);
                        }, function(result){
                            df.reject(result.message);
                        })
                    }
                    $scope.submitImport=function() {
                        if (!confirm("确定要导入这"+$scope.length+"个项目机会么")){ngDialog.closeAll();return;}
                        for (var i in $scope.body){
                            if ($scope.check[i]==1) {
                                if ($scope.exist[i]) {
                                    OppInfo.delete({infoid:$scope.getOppIdByOpcode($scope.body[i][1])},function(){
                                        $scope.uploadDate($scope.body[i]);
                                    },function(){
                                        df.reject(result.message);
                                    })
                                }
                                else $scope.uploadDate($scope.body[i]);
                            }
                        }
                        pm.then(function(data){
                            alert("成功导入"+data+"个机会");
                            $scope.loadAll(1);
                        },function(reason){
                            alert("导入失败:"+reason)
                        })
                        ngDialog.closeAll();
                    }
                }]
            })
        }
        $scope.upExcel = function (file) {
            if(!file)return;
            var reader = new FileReader();
            var name = file.name;
            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = XLSX.read(data, {type: 'binary'});
                var array=sheet_to_data(workbook);
                /* DO SOMETHING WITH workbook HERE */
            };
            reader.readAsBinaryString(file);
        };
    })